import 'dart:ffi';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/material.dart';
import 'package:flutter_fronter_service/enum/BuyOrCart.dart';
import 'package:widgets_easier/widgets_easier.dart';
import '../model/sku_entity.dart';
import 'package:get/get.dart';
import 'package:itwo_flutter_sku/itwo_flutter_sku.dart';

class SkuShowModal{

  late RxList<SkuEntity> skuList;
  late String goods_thumb;
  late int price;

  late Rx<String> selectedSkuImage = "".obs; //默认图片
  late Rx<String> selectedSkuName = "".obs; //默认规格
  late Rx<int> selectedSkuPrice = 0.obs; //默认价格
  late Rx<bool> selectedFinish = false.obs; //默认价格

  List<ISkuBean> skuBeanList = [];

  SkuShowModal({Key? key, required this.skuList, required this.goods_thumb,required this.price});

  //初始化数据
  void initData(){
    if(skuList.isNotEmpty && skuBeanList.isEmpty){
      for (var sku in skuList) {
        Map<String, dynamic> skuMap = sku.toJson();

        //解析规格
        sku.itemSpec.forEach((spec){
          skuMap[spec.name] = spec.value;
        });

        //取值
        skuMap.remove("itemSpec");
        skuMap.remove("itemImg");
        skuMap.remove("goodsName");
        skuMap.remove("goodsPrice");

        dynamic skuId = skuMap.remove('id');
        int skuStock = skuMap.remove('itemStock');

        //转型
        Map<String, String> stringSkuMap = skuMap.map((key, value) => MapEntry(key, value.toString()));
        skuBeanList.add(ISkuBean(skuId, stringSkuMap,iSkuStock: skuStock));

      }
    }
  }

  //根据id搜索
  SkuEntity? searchSkuById(int id) {
    // 迭代skuList搜索具有特定id的条目
    for (var sku in skuList) {
      if (sku.id == id) {
        return sku;
      }
    }
    // 如果没有找到匹配的条目，则返回null
    return null;
  }


  //设置sku组件
  showSkuModal(BuildContext context,BuyOrCart modalType) async{
    late RxMap<dynamic,dynamic> selectedChoice = {}.obs; //选择

    selectedSkuImage.value = goods_thumb;
    selectedSkuName.value = "";
    selectedFinish.value = false;
    selectedChoice["count"] = 1.0;
    initData();

     return await showModalBottomSheet(context: context,isScrollControlled: true, builder: (context) => Container(
        height: MediaQuery.of(context).size.height * 0.6, // 设置高度为屏幕高度的80%
        padding: const EdgeInsets.only(left: 10,top: 20,right: 20,bottom: 20),
        child: Column(
          children: [
            Obx(() =>
                ListTile(
                  leading: Image.network(selectedSkuImage.value),
                  title: Text(
                    !selectedFinish.value?"￥${price.toString()}~${(price+10).toString()}":"￥${price.toString()}",
                    overflow: TextOverflow.ellipsis,
                    maxLines: 1,
                    style: TextStyle(color: Colors.red),
                  ),
                  subtitle: Text(
                    "规格:${selectedSkuName.value}",
                    overflow: TextOverflow.ellipsis,
                    maxLines: 2,
                    style: const TextStyle(fontSize: 10, fontFamily: "sans-serif"),
                  ),
                )
            ),
            SizedBox(
              height: 250,
              child:Sku(
                skuBeanList: skuBeanList,
                zeroStockSelectEnable: false,
                onSelected: (sku){
                  if (sku != null) {
                    //不为空，查询相应的记录
                    SkuEntity? data = searchSkuById(sku.iSkuBeanId);
                    selectedSkuImage.value = data?.itemImg ?? goods_thumb;
                    selectedFinish.value = true;
                    selectedSkuName.value = sku.skuTagMap.values.join(' ') ?? "";
                    selectedChoice["id"] = sku.iSkuBeanId;
                  }else{
                    selectedSkuImage.value = goods_thumb;
                    selectedSkuName.value = "";
                  }
                },
              ),
            ),
            Container(
              width: double.infinity,
              child:  Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text("数量"),
                  CounterInput(
                    size: SizeEnum.small,
                    minValue: 1,
                    maxValue: 99,
                    onValueChanged: (oldValue, newValue) {
                      selectedChoice["count"] = newValue;
                    },
                    // controller: CounterInputController(),
                  ),
                ],
              ),
            ),
            SizedBox(height: 5,),
            Row(
              children: [
                Expanded(
                    flex:1,
                    child: modalType == BuyOrCart.Buy?ElevatedButton(
                        style: ButtonStyle(
                            backgroundColor: MaterialStateProperty.all(Color(0xfff23030)
                            ),
                            foregroundColor: MaterialStateProperty.all(Colors.white)),
                        onPressed: () => Navigator.of(context).pop(selectedChoice),
                        child: const Text('立即购买')
                    ):ElevatedButton(
                        style: ButtonStyle(
                            backgroundColor: MaterialStateProperty.all(Color(
                                0xffeeac81)
                            ),
                            foregroundColor: MaterialStateProperty.all(Colors.white)),
                        onPressed: () => Navigator.of(context).pop(selectedChoice),
                        child: const Text('加入购物车')
                    )),
              ],
            )
          ],
        )
    )
      );

  }
}